// 修改 showPage 函数，当显示历史订单页面时调用 viewHistoryOrders 函数
function showPage(pageId) {
    const pages = document.querySelectorAll('.page');
    pages.forEach(page => {
        page.style.display = 'none';
    });
    const page = document.getElementById(pageId);
    page.style.display = 'block';
    
    // 根据不同页面加载相应功能
    if (pageId === 'passenger-order') {
        initMap();
    } else if (pageId === 'history-orders') {
        viewHistoryOrders();
    } else if (pageId === 'all-history-orders') {
        viewAllOrders();
    }
}

// 高德地图相关变量
let map = null;
let startMarker = null;
let endMarker = null;
let drivingRoute = null;
let routePolyline = null;

// 初始化地图
function initMap() {
    // 如果地图已经初始化，则不再初始化
    if (map) return;
    
    // 默认武汉市中心坐标
    const wuhanCenter = [114.305469, 30.592849];
    
    // 创建地图实例
    //缩放级别：zoom: 12
    //高德地图支持的缩放级别范围是 3（全国范围）到 19（街道级别）。
    //值越大，地图显示越详细。
    map = new AMap.Map('map-container', {
        zoom: 12,
        center: wuhanCenter,
        resizeEnable: true//当浏览器窗口大小变化时，地图会自动重新渲染以适应新的尺寸。
    });
    
    // 添加控件
    map.plugin(['AMap.ToolBar', 'AMap.Scale'], function() {
        map.addControl(new AMap.ToolBar());
        map.addControl(new AMap.Scale());
    });
    
    // 创建《可拖动的》起点和终点标记
    startMarker = new AMap.Marker({
        position: null,  // 初始位置为空（后续可通过 setPosition 设置）
        map: map,        // 将标记添加到已初始化的地图实例中
        draggable: true, // 允许用户拖动标记点
        title: '起点',    // 鼠标悬停时显示的标题
        icon: new AMap.Icon({
            size: new AMap.Size(25, 34),      // 图标显示大小
            image: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png',
            imageSize: new AMap.Size(25, 34) // 原始图片大小
        })
    });
    
    endMarker = new AMap.Marker({
        position: null,
        map: map,
        draggable: true,
        title: '终点',
        icon: new AMap.Icon({
            size: new AMap.Size(25, 34),
            image: 'https://webapi.amap.com/theme/v1.3/markers/n/end.png',
            imageSize: new AMap.Size(25, 34)
        })
    });
    
    // 添加点击地图事件,
    map.on('click', function(e) {
        // e.lnglat 包含点击位置的经纬度 [经度, 纬度]
        console.log('地图点击事件触发，坐标：', e.lnglat);
        
        if (!startMarker.getPosition()) {
            // 设置起点
            startMarker.setPosition(e.lnglat);
            updateAddressFromLngLat(e.lnglat, 'start');
            console.log('已设置起点标记');
        } else if (!endMarker.getPosition()) {
            // 设置终点
            endMarker.setPosition(e.lnglat);
            updateAddressFromLngLat(e.lnglat, 'end');
            console.log('已设置终点标记，准备计算路线');
            // 自动计算路线
            setTimeout(calculateRoute, 500); // 稍微延迟以确保地址信息已更新
        } else {
            // 如果起点和终点都已经设置，则重置并设置新起点
            console.log('重置路线，设置新起点');
            resetRoute();
            startMarker.setPosition(e.lnglat);
            updateAddressFromLngLat(e.lnglat, 'start');
        }
    });
    
    // 为起点和终点标记添加拖拽结束事件
    //dragend 事件：由高德地图 API 触发，当标记拖拽操作结束时调用。
    startMarker.on('dragend', function(e) {
        updateAddressFromLngLat(e.lnglat, 'start');
        if (endMarker.getPosition()) {
            calculateRoute();
        }
    });
    
    endMarker.on('dragend', function(e) {
        updateAddressFromLngLat(e.lnglat, 'end');
        if (startMarker.getPosition()) {
            calculateRoute();
        }
    });
    
    // 添加搜索按钮，而不是使用AutoComplete
    document.getElementById('map-container').insertAdjacentHTML('afterend', 
        '<div style="margin: 10px 0;">' +
        '<button onclick="searchLocation(\'start\')" style="margin-right: 10px;">搜索起点</button>' +
        '<button onclick="searchLocation(\'end\')">搜索终点</button>' +
        '</div>'
    );
}

// 搜索位置
function searchLocation(type) {
    // 创建输入对话框
    const address = prompt(`请输入${type === 'start' ? '起点' : '终点'}位置:`);
    if (!address) return;
    
    // 使用地理编码服务查询位置
    AMap.plugin('AMap.Geocoder', function() {
        // 创建地理编码器实例
        const geocoder = new AMap.Geocoder();
        // 执行地理编码（地址转坐标）
        geocoder.getLocation(address, function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
                // 提取经纬度坐标
                const location = result.geocodes[0].location;
                
                if (type === 'start') {
                    startMarker.setPosition(location);
                    updateAddressFromLngLat(location, 'start');
                    if (endMarker.getPosition()) {
                        calculateRoute();
                    }
                } else {
                    endMarker.setPosition(location);
                    updateAddressFromLngLat(location, 'end');
                    if (startMarker.getPosition()) {
                        calculateRoute();
                    }
                }
            } else {
                alert('未找到该地址，请重新输入');
            }
        });
    });
}

// 根据经纬度更新地址
function updateAddressFromLngLat(lnglat, type) {
    console.log(`接收到坐标数据:`, lnglat);
    
    // 获取经纬度值
    const lat = lnglat.getLat ? lnglat.getLat() : lnglat.lat;
    const lng = lnglat.getLng ? lnglat.getLng() : lnglat.lng;
    
    // 确保经纬度值正确存储到隐藏字段
    if (type === 'start') {
        document.getElementById('start-lat').value = lat;
        document.getElementById('start-lng').value = lng;
        // 直接在输入框中显示经纬度
        document.getElementById('start-address').value = `${lng.toFixed(6)},${lat.toFixed(6)}`;
    } else {
        document.getElementById('end-lat').value = lat;
        document.getElementById('end-lng').value = lng;
        // 直接在输入框中显示经纬度
        document.getElementById('end-address').value = `${lng.toFixed(6)},${lat.toFixed(6)}`;
    }
    
    // 打印经纬度值，检查是否正确设置
    console.log(`设置${type}点: 纬度=${lat}, 经度=${lng}`);
}

// 计算路线
function calculateRoute() {
    // 获取表单数据
    const startLat = document.getElementById('start-lat').value;
    const startLng = document.getElementById('start-lng').value;
    const endLat = document.getElementById('end-lat').value;
    const endLng = document.getElementById('end-lng').value;
    const typeChoice = document.getElementById('order-type').value;
    
    console.log('计算路线，参数：', {
        startLat, startLng, endLat, endLng, typeChoice
    });
    
    if (!startLat || !startLng || !endLat || !endLng) {
        console.error('起点或终点坐标为空', {
            startLat, startLng, endLat, endLng
        });
        alert('请先设置起点和终点');
        return;
    }
    
    // 检查标记是否正确设置,同步地图标记（处理可能的标记与表单数据不一致）
    if (!startMarker.getPosition() || !endMarker.getPosition()) {
        console.error('标记未正确设置', {
            startMarker: startMarker.getPosition(),
            endMarker: endMarker.getPosition()
        });
        
        // 如果隐藏字段有值但标记没设置，则尝试设置标记
        if (startLat && startLng && !startMarker.getPosition()) {
            startMarker.setPosition(new AMap.LngLat(startLng, startLat));
        }
        
        if (endLat && endLng && !endMarker.getPosition()) {
            endMarker.setPosition(new AMap.LngLat(endLng, endLat));
        }
    }
    
    // 调用后端API获取路径和费用信息
    const url = `/api/map/direction?originLat=${startLat}&originLng=${startLng}&destinationLat=${endLat}&destinationLng=${endLng}&vehicleType=${typeChoice}`;
    console.log('发送请求：', url);
    
    // 移除已有的路线
    clearAllRoutes();

    //fetch发起一个网络请求
    fetch(url)//返回一个 Promise 对象，该对象代表了对请求的响应。
        //.then()是 Promise 对象的方法，用于在请求成功时执行回调函数。这里的
        // 回调函数接受一个参数response，它是一个包含服务器响应信息的对象。
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            return response.json();
        })
        .then(result => {
            console.log('路线计算结果：', result);
            if (result && result.paths && result.paths.length > 0) {
                // 创建路径选择控件
                createRouteSelector(result.paths);
                
                // 显示所有路径
                displayAllRoutes(result.paths);
                
                // 默认选择第一条路径
                selectRoute(0);
            } else {
                console.error('路线计算接口返回无效数据', result);
                alert('获取路线失败，请重试');
            }
        })
        .catch(error => {
            console.error('获取路线失败:', error);
            alert('获取路线失败，请重试：' + error.message);
        });
}

// 路线数组，存储所有绘制的路线对象
let routePolylines = [];
// 当前激活的路线索引 ，默认值-1表示未选择任何路线
let activeRouteIndex = -1;

// 清除所有路线
function clearAllRoutes() {
    if (routePolylines.length > 0) {
        routePolylines.forEach(polyline => {
            map.remove(polyline);
        });
    }
    routePolylines = [];
    
    // 移除路径选择器
    const existingSelector = document.getElementById('route-selector');
    if (existingSelector) {
        existingSelector.remove();
    }
}

// 创建路径选择控件
function createRouteSelector(paths) {
    // 移除已有的选择器
    const existingSelector = document.getElementById('route-selector');
    if (existingSelector) {
        existingSelector.remove();
    }
    
    // 格式化时间的辅助函数formatDuration
    function formatDuration(minutes) {
        console.log('原始的 minutes 值:', minutes);
        if (minutes < 1) {
            return `${Math.round(minutes * 60)}秒`;
        } else if (minutes < 60) {
            const remainingSeconds = Math.round((minutes % 1) * 60);
            return `${Math.floor(minutes)}分${remainingSeconds > 0 ? remainingSeconds + '秒' : ''}`;
        } else {
            const hours = Math.floor(minutes / 60);
            const remainingMinutes = Math.floor(minutes % 60);
            const remainingSeconds = Math.round((minutes % 1) * 60);
            return `${hours}小时${remainingMinutes > 0 ? remainingMinutes + '分' : ''}${remainingSeconds > 0 ? remainingSeconds + '秒' : ''}`;
        }
    }
    
    // 创建路径选择器
    const selectorHTML = `
        <div id="route-selector" style="margin-bottom: 15px; background: #f0f9ff; border-radius: 4px; padding: 10px;">
            <h3 style="margin-top: 0;">可选路线（${paths.length}条）</h3>
            <div class="route-options">
                ${paths.map((path, index) => `
                    <div class="route-option" style="margin-bottom: 10px; padding: 8px; border: 1px solid #ccc; border-radius: 4px; cursor: pointer;" onclick="selectRoute(${index})">
                        <strong>路线 ${index + 1}</strong>
                        <div>距离: ${path.distance.toFixed(1)} 公里</div>
                        <div>预计时间: ${formatDuration(path.duration)}</div>
                        <div>预估费用: ${path.fare.toFixed(2)} 元</div>
                    </div>
                `).join('')}
            </div>
        </div>
    `;
    
    // 添加到地图下方
    document.getElementById('route-info').insertAdjacentHTML('beforebegin', selectorHTML);
}

// 选择路线
function selectRoute(index) {
    console.log('选择路线:', index);
    
    // 更新当前活动路线索引
    activeRouteIndex = index;
    
    // 高亮显示选中的路线
    routePolylines.forEach((polyline, i) => {
        if (i === index) {
            polyline.setOptions({
                strokeColor: '#FF4500',  // 选中路线用橙红色
                strokeWeight: 8,
                zIndex: 100
            });
        } else {
            polyline.setOptions({
                strokeColor: '#0091ff',  // 未选中路线用蓝色
                strokeWeight: 5,
                zIndex: 50
            });
        }
    });
    
    // 更新路线信息显示
    const routeOptions = document.querySelectorAll('.route-option');
    routeOptions.forEach((option, i) => {
        if (i === index) {
            option.style.backgroundColor = '#e6f7ff';
            option.style.borderColor = '#91d5ff';
        } else {
            option.style.backgroundColor = '';
            option.style.borderColor = '#ccc';
        }
    });
    
    // 更新路线信息显示
    document.getElementById('route-info').style.display = 'block';
    document.getElementById('route-distance').textContent = routePolylines[index].pathData.distance.toFixed(1);
    
    // 格式化时间显示
    const durationInSeconds = routePolylines[index].pathData.duration;
    let formattedDuration;
    
    if (durationInSeconds < 60) {
        formattedDuration = `${durationInSeconds}秒`;
    } else if (durationInSeconds < 3600) {
        const minutes = Math.floor(durationInSeconds / 60);
        const seconds = durationInSeconds % 60;
        formattedDuration = `${minutes}分${seconds > 0 ? seconds + '秒' : ''}`;
    } else {
        const hours = Math.floor(durationInSeconds / 3600);
        const minutes = Math.floor((durationInSeconds % 3600) / 60);
        formattedDuration = `${hours}小时${minutes > 0 ? minutes + '分' : ''}`;
    }
    
    document.getElementById('route-duration').textContent = formattedDuration;
    document.getElementById('route-fare').textContent = routePolylines[index].pathData.fare.toFixed(2);
}

// 显示所有路径
function displayAllRoutes(paths) {
    paths.forEach((pathData, index) => {
        const polyline = displayRoute(pathData.path, index === 0, pathData);
        routePolylines.push(polyline);
    });
    
    // 调整视图以包含所有路线
    map.setFitView(routePolylines.concat([startMarker, endMarker]));
}

// 显示单条路径
function displayRoute(path, isActive, pathData) {
    console.log('解析路径数据:', path);
    
    try {
        let points = [];
        
        // 检查输出路径数据结构，便于调试
        console.log('路径数据结构:', JSON.stringify(path).substring(0, 500) + '...');
        
        // 检查是否有steps数组
        if (path.steps && path.steps.length > 0) {
            // 从路径数据中提取路径点
            let steps = path.steps;
            
            steps.forEach(step => {
                // 每个step中的polyline是一段路径的坐标点集合，用分号分隔
                if (step.polyline) {
                    const polyline = step.polyline.split(';');
                    polyline.forEach(point => {
                        const [lng, lat] = point.split(',');
                        // 确保lng和lat是有效的数字
                        if (!isNaN(parseFloat(lng)) && !isNaN(parseFloat(lat))) {
                            points.push([parseFloat(lng), parseFloat(lat)]);
                        }
                    });
                }
            });
        } 
        
        // 如果没有steps或没有提取到点，尝试使用直线连接起点和终点
        if (points.length === 0) {
            console.warn('未能从路径数据中提取有效的路径点，使用直线连接起终点');
            console.error('步骤数据:', path.steps ? path.steps.length : '无steps字段');
            
            // 在生成直线前，尝试通过别的方式获取线路
            if (path.polyline) {
                // 有些API版本可能直接在path中包含polyline
                console.log('尝试从path.polyline获取路径');
                const polyline = path.polyline.split(';');
                polyline.forEach(point => {
                    const [lng, lat] = point.split(',');
                    if (!isNaN(parseFloat(lng)) && !isNaN(parseFloat(lat))) {
                        points.push([parseFloat(lng), parseFloat(lat)]);
                    }
                });
            }
            
            // 如果仍然没有点，使用直线连接
            if (points.length === 0) {
                console.warn('尝试获取polyline失败，将使用直线连接起终点');
                
                // 获取起点和终点位置
                const startPos = startMarker.getPosition();
                const endPos = endMarker.getPosition();
                
                if (startPos && endPos) {
                    points = [
                        [startPos.getLng(), startPos.getLat()],
                        [endPos.getLng(), endPos.getLat()]
                    ];
                } else {
                    console.error('无法获取起点或终点坐标');
                    return null;
                }
            }
        }
        
        console.log('解析的路径点数量:', points.length);
        
        // 创建折线
        const routePolyline = new AMap.Polyline({
            path: points,
            // 是否显示轮廓
            isOutline: true,
            // 轮廓颜色
            outlineColor: '#ffeeee',
            // 轮廓宽度
            borderWeight: 2,
            // 折线颜色，根据isActive判断
            strokeColor: isActive ? '#FF4500' : '#0091ff',
            // 折线透明度
            strokeOpacity: 0.9,
            // 折线宽度，根据isActive判断
            strokeWeight: isActive ? 8 : 5,
            // 折线样式
            strokeStyle: 'solid',
            // 折线连接点样式
            lineJoin: 'round',
            // 折线端点样式
            lineCap: 'round',
            // 折线的zIndex，根据isActive判断
            zIndex: isActive ? 100 : 50
        });
        
        // 保存路径数据，方便后续使用
        routePolyline.pathData = pathData;
        
        // 添加到地图
        map.add(routePolyline);
        
        return routePolyline;
    } catch (error) {
        console.error('解析和显示路径时出错:', error);
        console.error('错误详情:', error.stack);
        return null;
    }
}

// 重置路线
function resetRoute() {
    if (routePolyline) {
        map.remove(routePolyline);
        routePolyline = null;
    }
    
    // 隐藏路线信息
    document.getElementById('route-info').style.display = 'none';
}

// 更新路线费用计算
function updateRouteFare() {
    const startLat = document.getElementById('start-lat').value;
    const startLng = document.getElementById('start-lng').value;
    const endLat = document.getElementById('end-lat').value;
    const endLng = document.getElementById('end-lng').value;
    
    if (startLat && startLng && endLat && endLng) {
        calculateRoute();
    }
}

// 登录
function login() {
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const userType = document.getElementById('user-type').value;
    if (!username || !password || !userType) {
        alert('用户名、密码和用户类型均为必填项，请填写完整！');
        return;
    }
    const data = {
        username,
        password
    };

    fetch('/api/users/login', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
        .then(response => response.json())
        .then(user => {
            const resultDiv = document.getElementById('login-result');
            if (user && user.userType === userType) {
                // 存储用户 ID
                localStorage.setItem('userId', user.id);
                // 存储用户类型
                localStorage.setItem('userType', userType);

                if (userType === 'user') {
                    showPage('user-page');
                } else if(userType === 'admin'){
                    showPage('admin-page');
                }
            } else {
                resultDiv.innerHTML = '登录失败，请检查用户名、密码和身份选择';
            }
        })
        .catch(error => {
            console.error('登录失败:', error);
            const resultDiv = document.getElementById('login-result');
            resultDiv.innerHTML = '登录失败，请稍后重试';
        });
}

//返回主页面
function goBackToMainPage() {
    const userType = localStorage.getItem('userType');
    if (userType === 'user') {
        showPage('user-page');
    } else if (userType === 'admin') {
        showPage('admin-page');
    }
}

// 注册
function register() {
    const username = document.getElementById('reg-username').value;
    const password = document.getElementById('reg-password').value;
    if (username === '' || password === '') {
        const resultDiv = document.getElementById('register-result');
        resultDiv.innerHTML = '用户名和密码不能为空';
        return;
    }
    const userType = document.getElementById('reg-user-type').value;

    const data = {
        username,
        password,
        userType
    };

    fetch('/api/users/register', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
        .then(response => response.json())
        .then(success => {
            const resultDiv = document.getElementById('register-result');
            if (success) {
                resultDiv.innerHTML = '注册成功，请返回登录页面';
            } else {
                resultDiv.innerHTML = '注册失败，用户名已存在';
            }
        })
        .catch(error => {
            console.error('注册失败:', error);
            const resultDiv = document.getElementById('register-result');
            resultDiv.innerHTML = '注册失败，请稍后重试';
        });
}

// 修改createOrder函数以包含路线信息
function createOrder() {
    const startLat = document.getElementById('start-lat').value;
    const startLng = document.getElementById('start-lng').value;
    const endLat = document.getElementById('end-lat').value;
    const endLng = document.getElementById('end-lng').value;
    const typeChoice = document.getElementById('order-type').value;
    const userId = localStorage.getItem('userId');
    
    // 输入检查
    if (!startLat || !startLng || !endLat || !endLng || !typeChoice || !userId) {
        alert('请确保所有必填项都已输入！');
        return;
    }
    
    // 检查是否已计算路线
    if (routePolylines.length === 0 || activeRouteIndex === -1) {
        alert('请先规划路线！');
        return;
    }
    
    // 从当前选择的路线获取距离和时间
    const selectedPathData = routePolylines[activeRouteIndex].pathData;
    const distance = selectedPathData.distance;
    const duration = selectedPathData.duration;
    
    // 对时间进行单位转换，API返回的是秒，需要转为分钟发送给后端
    const durationInMinutes = Math.round(duration / 60);
    
    const data = {
        userId,
        startLat,
        startLng,
        endLat,
        endLng,
        typeChoice,
        distance,
        duration: durationInMinutes // 转为分钟发送给后端
    };

    fetch('/api/orders', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
        .then(response => response.json())
        .then(order => {
            const resultDiv = document.getElementById('order-result');
            if (order) {
                const startTime = new Date(order.startTime).toLocaleString();
                resultDiv.innerHTML = `订单创建成功！订单编号：${order.id}<br>预估费用：${order.totalFare}元<br>打车起始时间：${startTime}`;
                if (order.assignedVehicle) {
                    resultDiv.innerHTML += `<br>已为您匹配车辆：${order.assignedVehicle.licensePlate}`;
                } else {
                    resultDiv.innerHTML += '<br>当前无可用车辆';
                }
                // 轮询检查订单状态
                const intervalId = setInterval(() => {
                    fetch(`/api/orders/${order.id}`)
                        .then(response => response.json())
                        .then(updatedOrder => {
                            if (updatedOrder.status === 'COMPLETED') {
                                const endTime = new Date(updatedOrder.endTime).toLocaleString();
                                resultDiv.innerHTML += `<br>行程已结束，结束时间：${endTime}`;
                                clearInterval(intervalId);
                            }
                        });
                }, 5000);
            } else {
                resultDiv.innerHTML = '当前无可用车辆';
            }
        })
        .catch(error => {
            console.error('下单失败:', error);
            const resultDiv = document.getElementById('order-result');
            resultDiv.innerHTML = '下单失败，当前无可用车辆';
        });
}

// 查看历史订单
function viewHistoryOrders() {
    const userId = localStorage.getItem('userId');
    if (!userId) {
        console.error('未获取到用户 ID');
        const resultDiv = document.getElementById('history-orders-result');
        resultDiv.innerHTML = '未获取到用户 ID，请重新登录';
        return;
    }

    fetch(`/api/orders/history/${userId}`)
        .then(response => response.json())
        .then(orders => {
            const resultDiv = document.getElementById('history-orders-result');
            if (orders && orders.length > 0) {
                // 计算统计数据
                let totalCost = 0;
                let totalDistance = 0;
                
                let html = '<table style="width:100%; border-collapse: collapse; margin-bottom: 20px;">';
                html += '<tr style="background-color: #f2f2f2;"><th style="padding: 8px; text-align: left; border: 1px solid #ddd;">订单编号</th><th style="padding: 8px; text-align: left; border: 1px solid #ddd;">状态</th><th style="padding: 8px; text-align: left; border: 1px solid #ddd;">起始时间</th><th style="padding: 8px; text-align: left; border: 1px solid #ddd;">结束时间</th><th style="padding: 8px; text-align: left; border: 1px solid #ddd;">距离(公里)</th><th style="padding: 8px; text-align: left; border: 1px solid #ddd;">费用(元)</th></tr>';
                
                orders.forEach(order => {
                    const startTime = order.startTime ? new Date(order.startTime).toLocaleString() : '无';
                    const endTime = order.endTime ? new Date(order.endTime).toLocaleString() : '无';
                    
                    // 累计统计数据
                    totalCost += order.totalFare || 0;
                    totalDistance += order.distance || 0;
                    
                    html += `<tr style="border: 1px solid #ddd;">
                        <td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${order.id}</td>
                        <td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${order.status}</td>
                        <td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${startTime}</td>
                        <td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${endTime}</td>
                        <td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${order.distance ? order.distance.toFixed(1) : '未知'}</td>
                        <td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${order.totalFare ? order.totalFare.toFixed(2) : '未知'}</td>
                    </tr>`;
                });
                html += '</table>';
                resultDiv.innerHTML = html;
                
                // 更新统计信息
                document.getElementById('total-user-cost').textContent = totalCost.toFixed(2);
                document.getElementById('total-user-rides').textContent = orders.length;
                document.getElementById('total-user-distance').textContent = totalDistance.toFixed(1);
            } else {
                resultDiv.innerHTML = '未找到历史订单';
                
                // 重置统计信息
                document.getElementById('total-user-cost').textContent = '0';
                document.getElementById('total-user-rides').textContent = '0';
                document.getElementById('total-user-distance').textContent = '0';
            }
        })
        .catch(error => {
            console.error('查询历史订单失败:', error);
            const resultDiv = document.getElementById('history-orders-result');
            resultDiv.innerHTML = '查询历史订单失败，请稍后重试';
        });
}

// 查看订单状态
function viewOrderStatus() {
    const orderId = document.getElementById('order-id').value;
    // 输入检查
    if (!orderId) {
        alert('请输入订单编号！');
        return;
    }
    fetch(`/api/orders/${orderId}`)
        .then(response => response.json())
        .then(order => {
            const resultDiv = document.getElementById('order-status-result');
            if (order) {
                const startTime = order.startTime ? new Date(order.startTime).toLocaleString() : '无';
                const endTime = order.endTime ? new Date(order.endTime).toLocaleString() : '无';
                resultDiv.innerHTML = `订单编号：${order.id}<br>订单状态：${order.status}<br>打车起始时间：${startTime}<br>行程结束时间：${endTime}`;
                if (order.assignedVehicle) {
                    resultDiv.innerHTML += `<br>匹配车辆：${order.assignedVehicle.licensePlate}`;
                }
                resultDiv.innerHTML += `<br>预估费用：${order.totalFare}元`;
            } else {
                resultDiv.innerHTML = '未找到该订单。';
            }
        })
        .catch(error => {
            console.error('查询订单失败:', error);
            const resultDiv = document.getElementById('order-status-result');
            resultDiv.innerHTML = '查询订单失败，请稍后重试';
        });
}

// 根据加盟类型更新表单显示
function updateJoinForm() {
    const joinType = document.getElementById('join-type').value;
    const vehicleInfoSection = document.getElementById('vehicle-info-section');
    
    if (joinType === 'COMPANY_VEHICLE') {
        // 公司提供车辆，只需要填写基本信息，不需要车牌
        document.getElementById('vehicle-license-plate').parentNode.style.display = 'none';
        // 显示说明信息
        const resultDiv = document.getElementById('join-result');
        resultDiv.innerHTML = '<div style="color: blue;">您选择了公司提供车辆方式加盟。系统将为您分配可用的公司车辆，如果当前没有可用车辆，将无法完成加盟。</div>';
    } else {
        // 司机自带车辆或自动驾驶车辆，需要填写完整车辆信息
        document.getElementById('vehicle-license-plate').parentNode.style.display = 'block';
        // 清空说明信息
        const resultDiv = document.getElementById('join-result');
        resultDiv.innerHTML = '';
        
        // 如果是自动驾驶车辆，显示特别说明
        if (joinType === 'AUTONOMOUS_VEHICLE') {
            resultDiv.innerHTML = '<div style="color: green;">您选择了自动驾驶车辆方式加盟。自动驾驶车辆将作为独立类型参与派单。</div>';
        }
    }
}

// 提交司机加盟申请
function applyForJoining() {
    const name = document.getElementById('driver-name').value;
    const licenseNumber = document.getElementById('license-number').value;
    const joinType = document.getElementById('join-type').value;
    const model = document.getElementById('model').value;
    const type = document.getElementById('type').value;
    const seats = document.getElementById('seats').value;
    const canCarpool = document.getElementById('can-carpool').checked;
    
    // 根据不同加盟类型检查输入
    let vehicleLicensePlate = '';
    if (joinType !== 'COMPANY_VEHICLE') {
        vehicleLicensePlate = document.getElementById('vehicle-license-plate').value;
        if (!vehicleLicensePlate) {
            alert('司机自带车辆和自动驾驶车辆需要填写车牌号！');
            return;
        }
    }
    
    // 基本输入检查
    if (!name || !licenseNumber ) {
        alert('请确保姓名、驾驶证号、车型、车辆类型和座位数都已填写！');
        return;
    }
    
    const data = {
        name,
        licenseNumber,
        joinType,
        vehicleLicensePlate,
        model,
        type,
        seats,
        canCarpool
    };

    fetch('/api/drivers', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
        .then(response => response.text())
        .then(message => {
            const resultDiv = document.getElementById('join-result');
            resultDiv.innerHTML = message;
        })
        .catch(error => {
            console.error('加盟申请失败:', error);
            const resultDiv = document.getElementById('join-result');
            resultDiv.innerHTML = '加盟申请失败，请稍后重试';
        });
}

// 查看所有司机信息
function viewAllDrivers() {
    // 获取所有司机信息
    fetch('/api/drivers')
        .then(response => response.json())
        .then(drivers => {
            const driverListDiv = document.getElementById('driver-list');
            if (drivers && drivers.length > 0) {
                let html = '<ul>';
                drivers.forEach(driver => {
                    html += `<li>司机名称：${driver.name}<br>驾驶证号：${driver.licenseNumber}<br>状态：${driver.status}<br>`;
                    if (driver.vehicle) {
                        html += `车牌号：${driver.vehicle.licensePlate}<br>车型：${driver.vehicle.model}<br>`;
                    }
                    html += '</li><li class="empty-line"></li>';
                });
                html += '</ul>';
                driverListDiv.innerHTML = html;
            } else {
                driverListDiv.innerHTML = '暂无司机信息';
            }
        })
        .catch(error => {
            console.error('获取司机信息失败:', error);
            const driverListDiv = document.getElementById('driver-list');
            driverListDiv.innerHTML = '获取司机信息失败，请稍后重试';
        });
}

// 新增自动驾驶车辆
function addAutonomousVehicle() {
    const licensePlate = document.getElementById('autonomous-license-plate').value;
    const model = document.getElementById('autonomous-model').value;
    // const type = document.getElementById('autonomous-type').value;
    const seats = document.getElementById('autonomous-seats').value;
    const canCarpool = document.getElementById('autonomous-can-carpool').checked;
    
    // 输入检查
    if (!licensePlate || !model || !seats) {
        alert('请确保车牌号、车型、车辆类型和座位数都已填写！');
        return;
    }
    
    const data = {
        licensePlate,
        model,
        // type,
        seats,
        canCarpool
    };

    fetch('/api/vehicles/autonomous', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.text())
    .then(result => {
        const resultDiv = document.getElementById('add-autonomous-result');
        resultDiv.innerHTML = result;
    })
    .catch(error => {
        console.error('添加自动驾驶车辆失败:', error);
        const resultDiv = document.getElementById('add-autonomous-result');
        resultDiv.innerHTML = '添加自动驾驶车辆失败，请稍后重试';
    });
}

// 新增公司车辆
function addCompanyVehicle() {
    const licensePlate = document.getElementById('company-license-plate').value;
    const model = document.getElementById('company-model').value;
    const type = document.getElementById('company-type').value;
    const seats = document.getElementById('company-seats').value;
    const canCarpool = document.getElementById('company-can-carpool').checked;
    
    // 输入检查
    if (!licensePlate || !model || !type || !seats) {
        alert('请确保车牌号、车型、车辆类型和座位数都已填写！');
        return;
    }
    
    const data = {
        licensePlate,
        model,
        type,
        seats,
        canCarpool
    };

    fetch('/api/vehicles/company', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.text())
    .then(result => {
        const resultDiv = document.getElementById('add-company-result');
        resultDiv.innerHTML = result;
    })
    .catch(error => {
        console.error('添加公司车辆失败:', error);
        const resultDiv = document.getElementById('add-company-result');
        resultDiv.innerHTML = '添加公司车辆失败，请稍后重试';
    });
}

// 管理员查看所有历史订单
function viewAllOrders() {
    fetch('/api/orders/all')
        .then(response => response.json())
        .then(orders => {
            const resultDiv = document.getElementById('all-history-orders-result');
            if (orders && orders.length > 0) {
                // 计算统计数据
                let totalRevenue = 0;
                let totalCommission = 0;
                let totalDistance = 0;
                
                let html = '<table style="width:100%; border-collapse: collapse; margin-bottom: 20px;">';
                html += '<tr style="background-color: #f2f2f2;"><th style="padding: 8px; text-align: left; border: 1px solid #ddd;">订单编号</th><th style="padding: 8px; text-align: left; border: 1px solid #ddd;">乘客</th><th style="padding: 8px; text-align: left; border: 1px solid #ddd;">状态</th><th style="padding: 8px; text-align: left; border: 1px solid #ddd;">车牌号</th><th style="padding: 8px; text-align: left; border: 1px solid #ddd;">起始时间</th><th style="padding: 8px; text-align: left; border: 1px solid #ddd;">结束时间</th><th style="padding: 8px; text-align: left; border: 1px solid #ddd;">距离(公里)</th><th style="padding: 8px; text-align: left; border: 1px solid #ddd;">总费用(元)</th><th style="padding: 8px; text-align: left; border: 1px solid #ddd;">公司抽成(元)</th></tr>';
                
                orders.forEach(order => {
                    const startTime = order.startTime ? new Date(order.startTime).toLocaleString() : '无';
                    const endTime = order.endTime ? new Date(order.endTime).toLocaleString() : '无';
                    const vehiclePlate = order.assignedVehicle ? order.assignedVehicle.licensePlate : '无';
                    
                    // 累计统计数据
                    totalRevenue += order.totalFare || 0;
                    totalCommission += order.commission || 0;
                    totalDistance += order.distance || 0;
                    
                    html += `<tr style="border: 1px solid #ddd;">
                        <td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${order.id}</td>
                        <td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${order.passengerName || '未知'}</td>
                        <td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${order.status}</td>
                        <td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${vehiclePlate}</td>
                        <td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${startTime}</td>
                        <td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${endTime}</td>
                        <td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${order.distance ? order.distance.toFixed(1) : '未知'}</td>
                        <td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${order.totalFare ? order.totalFare.toFixed(2) : '未知'}</td>
                        <td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${order.commission ? order.commission.toFixed(2) : '未知'}</td>
                    </tr>`;
                });
                html += '</table>';
                resultDiv.innerHTML = html;
                
                // 司机佣金 = 总收入 - 平台抽成
                const driverCommission = totalRevenue - totalCommission;
                
                // 更新统计信息
                document.getElementById('total-company-revenue').textContent = totalCommission.toFixed(2);
                document.getElementById('total-driver-commission').textContent = driverCommission.toFixed(2);
                document.getElementById('total-order-count').textContent = orders.length;
                document.getElementById('total-distance').textContent = totalDistance.toFixed(1);
            } else {
                resultDiv.innerHTML = '未找到历史订单';
                
                // 重置统计信息
                document.getElementById('total-company-revenue').textContent = '0';
                document.getElementById('total-driver-commission').textContent = '0';
                document.getElementById('total-order-count').textContent = '0';
                document.getElementById('total-distance').textContent = '0';
            }
        })
        .catch(error => {
            console.error('查询所有历史订单失败:', error);
            const resultDiv = document.getElementById('all-history-orders-result');
            resultDiv.innerHTML = '查询所有历史订单失败，请稍后重试';
        });
}

// 查看所有车辆信息
function viewAllVehicles() {
    fetch('/api/vehicles/all')
        .then(response => response.json())
        .then(vehicles => {
            displayVehicles(vehicles);
            updateVehicleStats(vehicles);
        })
        .catch(error => {
            console.error('获取车辆信息失败:', error);
            document.getElementById('vehicles-list').innerHTML = '获取车辆信息失败，请稍后重试';
        });
}

// 查看公司车辆
function viewCompanyVehicles() {
    fetch('/api/vehicles/company-owned')
        .then(response => response.json())
        .then(vehicles => {
            displayVehicles(vehicles);
            updateVehicleStats(vehicles);
        })
        .catch(error => {
            console.error('获取公司车辆信息失败:', error);
            document.getElementById('vehicles-list').innerHTML = '获取公司车辆信息失败，请稍后重试';
        });
}

// 按状态查看车辆
function viewVehiclesByStatus(status) {
    // 修正未分配状态的大小写问题
    const apiStatus = status === 'UNASSIGNED' ? 'unassigned' : status;
    
    fetch(`/api/vehicles/by-status?status=${apiStatus}`)
        .then(response => response.json())
        .then(vehicles => {
            displayVehicles(vehicles);
            // 不更新统计信息，因为这里只是查看部分车辆
        })
        .catch(error => {
            console.error('获取车辆信息失败:', error);
            document.getElementById('vehicles-list').innerHTML = '获取车辆信息失败，请稍后重试';
        });
}

// 显示车辆信息
function displayVehicles(vehicles) {
    const vehiclesListDiv = document.getElementById('vehicles-list');
    
    if (!vehicles || vehicles.length === 0) {
        vehiclesListDiv.innerHTML = '<p>没有找到车辆信息</p>';
        return;
    }
    
    let html = '<table style="width: 100%; border-collapse: collapse; margin-top: 20px;">';
    html += '<thead><tr style="background-color: #4CAF50; color: white; text-align: left;">';
    html += '<th style="padding: 8px; border: 1px solid #ddd;">车牌号</th>';
    html += '<th style="padding: 8px; border: 1px solid #ddd;">车型</th>';
    html += '<th style="padding: 8px; border: 1px solid #ddd;">类型</th>';
    html += '<th style="padding: 8px; border: 1px solid #ddd;">座位数</th>';
    html += '<th style="padding: 8px; border: 1px solid #ddd;">拼车</th>';
    html += '<th style="padding: 8px; border: 1px solid #ddd;">自动驾驶</th>';
    html += '<th style="padding: 8px; border: 1px solid #ddd;">公司车辆</th>';
    html += '<th style="padding: 8px; border: 1px solid #ddd;">状态</th>';
    //html += '<th style="padding: 8px; border: 1px solid #ddd;">位置</th>';
    html += '</tr></thead><tbody>';
    
    vehicles.forEach(vehicle => {
        html += '<tr style="border: 1px solid #ddd;">';
        html += `<td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${vehicle.licensePlate}</td>`;
        html += `<td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${vehicle.model || '未知'}</td>`;
        html += `<td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${vehicle.type || '未知'}</td>`;
        html += `<td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${vehicle.seats}</td>`;
        html += `<td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${vehicle.canCarpool ? '是' : '否'}</td>`;
        html += `<td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${vehicle.isAutonomous ? '是' : '否'}</td>`;
        html += `<td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${vehicle.companyOwned ? '是' : '否'}</td>`;
        html += `<td style="padding: 8px; text-align: left; border: 1px solid #ddd;">${getStatusText(vehicle.status)}</td>`;
        //html += `<td style="padding: 8px; text-align: left; border: 1px solid #ddd;">经度: ${vehicle.longitude.toFixed(4)}, 纬度: ${vehicle.latitude.toFixed(4)}</td>`;
        html += '</tr>';
    });
    
    html += '</tbody></table>';
    vehiclesListDiv.innerHTML = html;
}

// 获取车辆状态对应的中文文本
function getStatusText(status) {
    switch(status) {
        case 'AVAILABLE':
            return '可用';
        case 'ON_TRIP':
            return '在途';
        case 'MAINTENANCE':
            return '维护中';
        case 'UNASSIGNED':
            return '未分配';
        default:
            return status || '未知';
    }
}

// 更新车辆统计信息
function updateVehicleStats(vehicles) {
    if (!vehicles || vehicles.length === 0) {
        return;
    }
    
    document.getElementById('total-vehicles').textContent = vehicles.length;
    
    const availableCount = vehicles.filter(v => v.status === 'AVAILABLE').length;
    const onTripCount = vehicles.filter(v => v.status === 'ON_TRIP').length;
    const autonomousCount = vehicles.filter(v => v.isAutonomous).length;
    // 修改为统计公司拥有且未分配的车辆数量
    const companyUnassignedCount = vehicles.filter(v => v.companyOwned && v.status === 'unassigned').length;
    
    document.getElementById('available-vehicles').textContent = availableCount;
    document.getElementById('ontrip-vehicles').textContent = onTripCount;
    document.getElementById('autonomous-vehicles').textContent = autonomousCount;
    document.getElementById('company-vehicles').textContent = companyUnassignedCount;
}